import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button,  message, Modal } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import CreateForm from './CreateForm';
import UpdateForm from './UpdateForm';
import { getReasonTable, removeReason, updateConfig } from '../service.js';

import styles from '../index.less'
import AuthComponent from '@/components/Authorized/AuthComponent';

const { confirm } =Modal

const Tables = () => {
  const [createModalVisible, handleCreateModalVisible] = useState(false); // 新建弹框
  const [updateModalVisible, handleUpdateModalVisible] = useState(false); //  编辑
  const [updateData, saveUpdateData] = useState({}) // 编辑数据
  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选
  const [dataSource, handleDataSource] = useState([]) // 列表数据

  const actionRef = useRef();
  const ref = useRef();
  const height = document.body.clientHeight - 356.5; // 表格高度自适应

  const columns = [
    {
      title: '拒绝原因',
      dataIndex: 'content',
    },
    {
      title: '创建人',
      dataIndex: 'createUser',
    },
    {
      title: '更新人',
      dataIndex: 'updateUser',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      // sorter: true,
      valueType: 'dateTime',
    },
  ];
  // 获取列表
  const getList = ()=> {
    getReasonTable({type: '1'}).then(res=> {
      res && res.map(item => {
        if (!item.updateTime) {
          item.updateTime = item.createTime
          item.updateUser = item.createUser
          return item
        }
      })
      handleDataSource(res)
    })
  }
  // 添加更新
  const handleSubmit = async (fields, text) => {
    const hide = message.loading(`正在${text}`);
    try {
      const res = await updateConfig({
        actConfigInfo: {...fields, type: '1'},
      });
      if (res.code === '1') {
        hide();
        message.error(res.msg);
      } else {
        hide()
        message.success(`${text}成功`);
        return true;
      }
    } catch (error) {
      hide();
      message.error(`已有重复数据, ${text}失败请重试！`);
    }
  };
  // 删除
  const handleRemove = async (selectedRows) => {
    try {
      await removeReason({
        ids: selectedRows.map(row => row.id).toString(),
      });
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
    }
  };
  useEffect(()=>{
    getList()
  },[])

  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  return (
    <div>
      <ProTable
        className={`rest-pro-table-form-compact`}
        size='small'
        // options={{density: false, fullScreen:true, reload: (()=>{
        //   getList()
        //   console.log('refresh...');
        // }), setting:true}}
        options={{ density: false, fullScreen: true, reload:false, setting: true }}
        rowKey='id'
        scroll={{ y:height }}
        search={false}
        headerTitle={
          <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>拒绝原因</span>
        }
        actionRef={actionRef}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={dataSource}
        pagination={{
          showSizeChanger: true,
        }}
        toolBarRender={() => [
          <Button style={{marginRight:10}} icon='plus' type="primary" onClick={() => {
            handleCreateModalVisible(true)}}>
              新建
          </Button>,
          <Button style={{marginRight:10}}  icon='edit' onClick={() => {
            if (selectedRowKeys.length === 0) {
              message.error('请选择编辑的条目')
            } else if (selectedRowKeys.length > 1) {
              message.error('只能选择一条进行编辑')
            } else {
              handleUpdateModalVisible(true)
              saveUpdateData(selectedRows[0])
            }
          }}>编辑</Button>,
          <Button icon='delete' onClick={() => {
            if (selectedRowKeys.length === 0) {
              message.error("请选择删除的条目")
            } else {
              confirm({
                title: '提示',
                content: '确认操作后，该数据将被删除，无法使用，你还要继续吗？',
                cancelText: '取消',
                okText: '确认',
                onOk: async () => {
                  const result = await handleRemove(selectedRows);
                  if(result){
                    getList()
                    handleSelectedRows([])
                    handleSelectedRowKeys([])
                  }
                }
              })
            }
          }}>删除</Button>
        ]}
      />

      {/* 新建 */}
      <CreateForm
        onSubmit={async value => {
          const success = await handleSubmit(value, '添加');
          if (success) {
            handleCreateModalVisible(false);
            getList()
            handleSelectedRowKeys([])
            handleSelectedRows([])
          }
        }}
        onCancel={() => handleCreateModalVisible(false)}
        createModalVisible={createModalVisible}
      />
      {/* 编辑 */}
      <UpdateForm
        onSubmit={async value => {
          const success = await handleSubmit(value, '编辑');
          if (success) {
            handleUpdateModalVisible(false);
            getList()
            handleSelectedRowKeys([])
            handleSelectedRows([])
          }
        }}
        onCancel={() => handleUpdateModalVisible(false)}
        updateModalVisible={updateModalVisible}
        updateData={updateData}
      />
    </div>
  );
};

export default Form.create()(Tables);
